package cn.alone.basic.service.impl;

import cn.alone.basic.BusinessException;
import cn.alone.basic.constant.BaseConstants;
import cn.alone.basic.service.IVerifyCodeService;
import cn.alone.basic.util.StrUtils;
import cn.alone.user.domain.User;
import cn.alone.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 发送验证码
 * @author lanan
 */
@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void sendSmsCode(Map<String,String> params) {
        String phone = params.get("phone");
        String type = params.get("type");
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(type)) {
            throw new BusinessException("手机号不能为空!!!!");
        }
        String businessKey = "";
        /*判断是注册还是绑定*/
        if ("register".equals(type)) {
            User user = userMapper.loadByPhone(phone);
            if (user != null) {
                throw new BusinessException("用户已存在,请直接登录!!!");
            }
            businessKey = BaseConstants.BUSINESS_REGISTER_PREFIX + phone;
            /*绑定微信*/
        } else if ("binder".equals(type)) {
            businessKey = BaseConstants.BUSINESS_BINDER_PREFIX + phone;
        }
        sendCode(businessKey);
    }


    public void sendCode(String businessKey){
        String key = businessKey;
        Object codeValueTmp = redisTemplate.opsForValue().get(key);
        String code = "";
        if(codeValueTmp != null){
            Long oldTime = Long.valueOf(((String)codeValueTmp).split(":")[1]);
            if(System.currentTimeMillis() - oldTime <= 1 * 60 * 1000){
                throw new BusinessException("操作异常!");
            }
            code = ((String)codeValueTmp).split(":")[0];
        }else{
            code = StrUtils.getComplexRandomString(4);
        }
        String codeVal = code + ":" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, codeVal, 3, TimeUnit.MINUTES);
        System.out.println("您的验证码是:" + code + ",三分钟内有效");

    }
}
